<?php
include_once('./inc/config.php');
if(!is_logged_in()) redirect('index.php');	

$mode = $_GET['mode'];
$d_id = (int) $_GET['id'];
$set_value = $_GET['set_value'];

if(empty($d_id) && $set_value == true) redirect('index.php');

if($set_value == true)
{
	$ses_arr = array('domain_sel');
	if(!session_register($ses_arr))
		session_register($ses_arr);

	$_SESSION['domain_sel'] = get_sel_domain($d_id);
}


$actions = array();
switch($mode)
{
	default:
		$actions = get_all_info();
 	break;
	
	case 'export':
		export_all_info();
		exit;
	break;
	
	case 'export_excel':
		export_all_info('excel');
		exit;
	break;
}

//--------------------------------------------------------

/** 
 * Export All info
 *
 * @descp Export all info for this domain
 * @access public
 * @param  NA	 
 * @return void
 */
function export_all_info($type='word')
{
	global $dbobj, $proj_config;
	$ret = array();
	$an_code = $_SESSION['domain_sel']['c_code'];
	
	//Get IP's
	$unq_ip_data = get_unique_ip_add($an_code);
	$ret = array_merge($ret,$unq_ip_data);
	
	//Get Pages URL
	$pg_urls_data = get_unique_page_urls($an_code);
	$ret = array_merge($ret,$pg_urls_data);	 
	
	//Get page referrals
	$ref_data = get_sum_ref($an_code);
	$ret = array_merge($ret,$ref_data);
	
	//Get User Agent and Browser	
	$brow_data = get_sum_browser($an_code);
	$ret = array_merge($ret,$brow_data);
	
	//Get search engine
	$sr_eng_data = get_sum_search_eng($an_code);
	$ret = array_merge($ret,$sr_eng_data);
	
	//Get highest traffic stats
	$pg_traffic = get_high_traffic_data($an_code);
	$ret = array_merge($ret,$pg_traffic);
	
	//Get max, min, average time on page
	$pg_time = get_time_on_page($an_code);
	$ret = array_merge($ret,$pg_time);
	
	$actions = $ret;
	if($type == 'word'){
		$actions['download_file'] = date('d_M_Y').'_webseo_analytics.doc';		
	}else{
		$actions['download_file'] = date('d_M_Y').'_webseo_analytics.xls';		
	}	
	$actions['download_file_type'] = $type;		
	include(BASEPATH . 'views/an_list_export.php');//include body part
}

//--------------------------------------------------------

/** 
 * Get All info
 *
 * @descp Get all info for this url
 * @access public
 * @param  NA	 
 * @return void
 */
function get_all_info()
{
	global $dbobj, $proj_config;
	$ret = array();
	$an_code = $_SESSION['domain_sel']['c_code'];
	
	//Get IP's
	$unq_ip_data = get_unique_ip_add($an_code);
	$ret = array_merge($ret,$unq_ip_data);
	
	//Get Pages URL
	$pg_urls_data = get_unique_page_urls($an_code);
	$ret = array_merge($ret,$pg_urls_data);	 
	
	//Get page referrals
	$ref_data = get_sum_ref($an_code);
	$ret = array_merge($ret,$ref_data);
	
	//Get User Agent and Browser	
	$brow_data = get_sum_browser($an_code);
	$ret = array_merge($ret,$brow_data);
	
	//Get search engine
	$sr_eng_data = get_sum_search_eng($an_code);
	$ret = array_merge($ret,$sr_eng_data);
	
	//Get highest traffic stats
	$pg_traffic = get_high_traffic_data($an_code);
	$ret = array_merge($ret,$pg_traffic);
	
	//Get max, min, average time on page
	$pg_time = get_time_on_page($an_code);
	$ret = array_merge($ret,$pg_time);
			
	return $ret;	
}

//--------------------------------------------------------

/** 
 * Get page URL
 *
 * @descp Get count and data of unique page urls
 * @access public
 * @param  string
 * @return array
 */
function get_unique_page_urls($an_code = '')
{
	global $dbobj, $proj_config;
	$query = "SELECT COUNT(DISTINCT(location_href)) as info 
				FROM ".TBL_ANA_DATA." 
				WHERE an_code = '".$an_code."'
				AND location_href != ''";
	$temp = $dbobj->MySQLDB_GetData($query);
	$ret['loc_href_cnt'] = $temp['info'];
	$ret['loc_href_data'] = array();
	if($ret['loc_href_cnt'] > 0)
	{
		//Get Referrals data array if the count is greater than 0
		$query = "SELECT DISTINCT(location_href) as info 
					FROM ".TBL_ANA_DATA." 
					WHERE an_code = '".$an_code."'
					AND location_href != ''
					ORDER BY an_created DESC
					LIMIT ".MAX_SUMMARY_LIMT;
		// Perform Query	
		$result = $dbobj->MySQLDB_GetData($query,'ARRAY');	
		// Get num rows from the result set	
		$no_rows = $dbobj->MySQLDB_Numrows();				
		if($no_rows > 0)
		{
			$ret['loc_href_data'] = $result;	
		}
	}
	
	return $ret;
}

//--------------------------------------------------------

/** 
 * Get unique IP address
 *
 * @descp Get count and data of unique IP address
 * @access public
 * @param  string
 * @return array
 */
function get_unique_ip_add($an_code = '')
{
	global $dbobj, $proj_config;
	$query = "SELECT COUNT(DISTINCT(ip_add)) as info 
				FROM ".TBL_ANA_DATA." 
				WHERE an_code = '".$an_code."'
				AND ip_add != ''";
	$temp = $dbobj->MySQLDB_GetData($query);
	$ret['uniq_ip_cnt'] = $temp['info'];
	$ret['uniq_ip_data'] = array();
	if($ret['uniq_ip_cnt'] > 0)
	{
		//Get Referrals data array if the count is greater than 0
		$query = "SELECT DISTINCT(ip_add) as info 
					FROM ".TBL_ANA_DATA." 
					WHERE an_code = '".$an_code."'
					AND ip_add != ''
					ORDER BY an_created DESC
					LIMIT ".MAX_SUMMARY_LIMT;
		// Perform Query	
		$result = $dbobj->MySQLDB_GetData($query,'ARRAY');	
		// Get num rows from the result set	
		$no_rows = $dbobj->MySQLDB_Numrows();				
		if($no_rows > 0)
		{
			$ret['uniq_ip_data'] = $result;	
		}
	}
	
	return $ret;
}

//--------------------------------------------------------

/** 
 * Get high traffic data
 *
 * @descp Get count when was the highest page visits
 * @access public
 * @param  string
 * @return array
 */
function get_high_traffic_data($an_code = '')
{
	global $dbobj, $proj_config;
	
	$temp['info'] = '';
	$temp['cnt'] = 0;
	$query = "SELECT an_created AS info, count( an_id ) AS cnt
				FROM ".TBL_ANA_DATA."
				WHERE an_code = '".$an_code."'
				GROUP BY date_format( an_created , '%d%m%y' )
				ORDER BY cnt DESC
				LIMIT 1";
	$temp = $dbobj->MySQLDB_GetData($query);
	if(!empty($temp['info']))
	{
		//format the date is human readable format
		$temp['info'] = date('jS D M Y',strtotime($temp['info']));
	}	
	$ret['high_traffic'] = $temp;
	
	$ret['total_pg_visits'] = 0;
	$query = "SELECT count( an_id ) AS info
				FROM ".TBL_ANA_DATA."
				WHERE an_code = '".$an_code."'";
	$temp = $dbobj->MySQLDB_GetData($query);
	if(!empty($temp['info']))
	{
		$ret['total_pg_visits'] = $temp['info'];
	}
		
	return $ret;
}	

//--------------------------------------------------------

/** 
 * Get time on page by a vistor
 *
 * @descp Get count if time on page by a vistor
 * @access public
 * @param  string
 * @return array
 */
function get_time_on_page($an_code = '')
{
	global $dbobj, $proj_config;
	
	$ret['max_time_on_pg'] = 0;
	$ret['min_time_on_pg'] = 0;
	$ret['avg_time_on_pg'] = 0;
	//Max time on page
	$query = "SELECT max( `total_time` ) as info
				FROM ".TBL_TIME_PG."
				WHERE `an_code` = '".$an_code."'
				AND total_time > 0.00";
	$temp = $dbobj->MySQLDB_GetData($query);
	if(!empty($temp['info']))
	{
		$ret['max_time_on_pg'] = $temp['info'];
	}
	
	//Min time on page
	$query = "SELECT min( `total_time` ) as info
				FROM ".TBL_TIME_PG."
				WHERE `an_code` = '".$an_code."'
				AND total_time > 0.00";
	$temp = $dbobj->MySQLDB_GetData($query);
	if(!empty($temp['info']))
	{
		$ret['min_time_on_pg'] = $temp['info'];
	}
	
	//Average time on page
	$query = "SELECT avg( `total_time` ) as info
				FROM ".TBL_TIME_PG."
				WHERE `an_code` = '".$an_code."'
				AND total_time > 0.00";
	$temp = $dbobj->MySQLDB_GetData($query);
	if(!empty($temp['info']))
	{
		$ret['avg_time_on_pg'] = round($temp['info'],2);
	}
	return $ret;
}	

//--------------------------------------------------------

/** 
 * Get Summary data for Referrals
 *
 * @descp Get Summary data for Referrals with count and data set
 * @access public
 * @param  string
 * @return array
 */
function get_sum_ref($an_code = '')
{
	global $dbobj, $proj_config;
	//Get Referrals
	$query = "SELECT COUNT(DISTINCT(doc_ref)) as info 
				FROM ".TBL_ANA_DATA." 
				WHERE an_code = '".$an_code."'
				AND doc_ref != ''";
	$temp = $dbobj->MySQLDB_GetData($query);
	$ret['ref_cnt'] = $temp['info'];
	$ret['ref_data'] = array();
	if($ret['ref_cnt'] > 0)
	{
		//Get Referrals data array if the count is greater than 0
		$query = "SELECT DISTINCT(doc_ref) as info 
					FROM ".TBL_ANA_DATA." 
					WHERE an_code = '".$an_code."'
					AND doc_ref != ''
					ORDER BY an_created DESC
					LIMIT ".MAX_SUMMARY_LIMT;
		// Perform Query	
		$result = $dbobj->MySQLDB_GetData($query,'ARRAY');	
		// Get num rows from the result set	
		$no_rows = $dbobj->MySQLDB_Numrows();				
		if($no_rows > 0)
		{
			$ret['ref_data'] = $result;	
		}
	}
	
	return $ret;
}	
	
//--------------------------------------------------------

/** 
 * Get Summary data for Browsers
 *
 * @descp Get Summary data for Browserswith count and data set
 * @access public
 * @param  string
 * @return array
 */
function get_sum_browser($an_code = '')
{
	global $dbobj, $proj_config;
	//Get Referrals
	$query = "SELECT COUNT(DISTINCT(br_userAgent)) as info 
				FROM ".TBL_ANA_DATA." 
				WHERE an_code = '".$an_code."'
				AND br_userAgent != ''";
	$temp = $dbobj->MySQLDB_GetData($query);
	$ret['us_ag_cnt'] = $temp['info'];
	$ret['us_ag_data'] = array();
	if($ret['us_ag_cnt'] > 0)
	{
		//Get Referrals data array if the count is greater than 0
		$query = "SELECT DISTINCT(br_userAgent) as info 
					FROM ".TBL_ANA_DATA." 
					WHERE an_code = '".$an_code."'
					AND br_userAgent != ''
					ORDER BY an_created DESC
					LIMIT ".MAX_SUMMARY_LIMT;
		// Perform Query	
		$result = $dbobj->MySQLDB_GetData($query,'ARRAY');	
		// Get num rows from the result set	
		$no_rows = $dbobj->MySQLDB_Numrows();				
		$result_filter = array();
		if($no_rows > 0)
		{
			foreach($result as $key => $val)
			{
				$result[$key]['br'] = browser_check( $val['info'], true);//push the data in the same array
			}
			$ret['us_ag_data'] = $result;	
		}
	}
	
	return $ret;
}

//--------------------------------------------------------

/** 
 * Get Summary data for search engines
 *
 * @descp Get Summary data for Browserswith count and data set
 * @access public
 * @param  string
 * @return array
 */
function get_sum_search_eng($an_code = '')
{
	global $dbobj, $proj_config;
	//Get Referrals
	$query = "SELECT COUNT(DISTINCT(doc_ref)) as info 
				FROM ".TBL_ANA_DATA." 
				WHERE an_code = '".$an_code."'
				AND doc_ref != ''";
	$temp = $dbobj->MySQLDB_GetData($query);
	$ret['sr_eng_cnt'] = $temp['info'];
	$ret['sr_eng_data'] = array();
	if($ret['sr_eng_cnt'] > 0)
	{
		//Get Referrals data array if the count is greater than 0
		$query = "SELECT DISTINCT(doc_ref) as info 
					FROM ".TBL_ANA_DATA." 
					WHERE an_code = '".$an_code."'
					AND doc_ref != ''
					ORDER BY an_created DESC
					LIMIT ".MAX_SUMMARY_LIMT;
		// Perform Query	
		$result = $dbobj->MySQLDB_GetData($query,'ARRAY');	
		// Get num rows from the result set	
		$no_rows = $dbobj->MySQLDB_Numrows();				
		$result_filter = array();
		if($no_rows > 0)
		{
			foreach($result as $key => $val)
			{
				$br_d = search_engine_check( $val['info'], true);//push the data in the same array
				if(!empty($br_d))
				{
					$result[$key]['br'] =  $br_d;
				}
			}
			$ret['sr_eng_data'] = $result;	
		}
	}
	
	return $ret;
}
	
//--------------------------------------------------------

/** 
 * Get selected domain
 *
 * @descp Get domain based on the user id and id selected
 * @access public
 * @param  int	 
 * @return void
 */
function get_sel_domain($d_id = 0)
{
	global $dbobj, $proj_config;
	$d_id = (int) $d_id ;
	$set = array();
	$query = "SELECT COUNT(d_id) as info
				FROM ".TBL_DOMAINS."
				WHERE 	user_id  = '".$_SESSION['user_id']."'	
				AND d_id   = '".$d_id ."'	
				";
	$temp = $dbobj->MySQLDB_GetData($query);
	$no_rows = $temp['info'];						
	if($no_rows > 0)
	{		
		$query = "SELECT d_id,d_name,c_code
				FROM ".TBL_DOMAINS."
				WHERE 	user_id  = '".$_SESSION['user_id']."'	
				AND d_id   = '".$d_id ."'	
				";		
		$set = $dbobj->MySQLDB_GetData($query);		
	}
	else
	{
		redirect('index.php');
	}
	
	return (isset($set['d_name']))?$set:'';
}

/************************************************************/
//get data set for flash chart
//get pie charts data

//--------------------------------------------------------

/** 
 * Get OFC Chart Data for Year
 *
 * @descp Get OFC jason array data for Year
 * @access public
 * @param  NA	 
 * @return void
 */
function get_ofc_data_year()
{
	global $dbobj, $proj_config;
	
	//initialize the array for the current day and month
	$month = date('M-Y',mktime(23,59,59,date('m'),(date('d')-1),date('Y')));
	$monthnos[$month] = 0;
	$montharr[] = $month;
	//No we only have to run the lopp for the remaining 11 months
	for($i = 1; $i <=11 ; $i++){
		$month = date('M-Y', mktime(0 , 0 , 0 , (date('m')-$i),1,date('Y')) );
		$monthnos[$month] = 0;
		$montharr[] = $month;
	}
	//This will give us yesterdays timestamp
	$curr_day_of_yr = date("Y-m-d H:i:s",mktime(23,59,59,date('m'),(date('d')-1),date('Y')));		
	//This will give us timestamp from yesterday till last 12 months
	$last_day_of_yr = date("Y-m-d H:i:s",mktime(0,0,0,(date('m')-11),1,date('Y')));
			
	$an_code = $_SESSION['domain_sel']['c_code'];
	$query = "SELECT DATE_FORMAT(an_created, '%b-%Y') as strmon, COUNT(an_id) as info
		FROM ".TBL_ANA_DATA."
		WHERE an_code = '".$an_code."'
		AND (
			DATE_FORMAT(an_created, '%Y-%m-%d %H:%i:%s') <= '".$curr_day_of_yr."'		
			AND
			DATE_FORMAT(an_created, '%Y-%m-%d %H:%i:%s') >= '".$last_day_of_yr."'
		)		
		GROUP BY DATE_FORMAT(an_created, '%b-%Y')
		";		
	
	$temp = $dbobj->MySQLDB_GetData($query,'ARRAY');
	foreach($temp as $val){
		$monthnos[$val['strmon']] = (int) $val['info'];
	}
	
	$ofc_title = 'Statistics - At a glance ('.date("M-Y",strtotime($curr_day_of_yr)).' To '.date("M-Y",strtotime($last_day_of_yr)).')';
	$ofc_labels_x = array_keys($monthnos);
	$ofc_values_x = array_values($monthnos);
	$ofc_range_max = max($ofc_values_x)+5;
	$ofc_range_step = ceil($ofc_range_max/10);
	$ofc_legend_x = 'Months in the Year ('.date("M-Y",strtotime($curr_day_of_yr)).' To '.date("M-Y",strtotime($last_day_of_yr)).')';;
	$ofc_legend_y = 'Visitors';	
	$ofc_unique_id = 'ofc_yr';	
	include(BASEPATH . 'views/ofc_chart.php');
}

//--------------------------------------------------------

/** 
 * Get OFC Chart Data for Current Month
 *
 * @descp Get OFC jason array data for Current Month
 * @access public
 * @param  NA	 
 * @return void
 */
function get_ofc_data_cur_m()
{
	global $dbobj, $proj_config;
	//get days in a month
	$no_of_days = days_in_month(date('m'));
	for($i = 1; $i <= $no_of_days ; $i++){		
		$monthnos[$i] = 0;
		$montharr[] = $i;
	}
	$an_code = $_SESSION['domain_sel']['c_code'];
	$query = "SELECT DATE_FORMAT(an_created, '%e') as strday, COUNT(an_id) as info
		FROM ".TBL_ANA_DATA."
		WHERE an_code = '".$an_code."'
		AND DATE_FORMAT(an_created, '%Y-%m') = '".date('Y-m')."'		
		GROUP BY DATE_FORMAT(an_created, '%e')
		";		
	$temp = $dbobj->MySQLDB_GetData($query,'ARRAY');
	foreach($temp as $val){
		$monthnos[$val['strday']] = (int) $val['info'];
	}
	$ofc_title = 'Statistics - for the current month '.date("F-Y");
	$ofc_labels_x = array_keys($monthnos);
	$ofc_values_x = array_values($monthnos);
	$ofc_range_max = max($ofc_values_x)+5;
	$ofc_range_step = ceil($ofc_range_max/10);
	$ofc_legend_x = 'Days in the current month - '.date('F-Y');
	$ofc_legend_y = 'Visitors';	
	$ofc_unique_id = 'ofc_cur_m';	
	include(BASEPATH . 'views/ofc_chart.php');
}

//--------------------------------------------------------

/** 
 * Get OFC Chart Data for Last Month
 *
 * @descp Get OFC jason array data for Last Month
 * @access public
 * @param  NA	 
 * @return void
 */
function get_ofc_data_last_m()
{
	global $dbobj, $proj_config;
	//get days in a month
	$last_month_time = strtotime("Last Month");
	$no_of_days = days_in_month(date("m",$last_month_time));
	for($i = 1; $i <= $no_of_days ; $i++){		
		$monthnos[$i] = 0;
		$montharr[] = $i;
	}
	$an_code = $_SESSION['domain_sel']['c_code'];
	$query = "SELECT DATE_FORMAT(an_created, '%e') as strday, COUNT(an_id) as info
		FROM ".TBL_ANA_DATA."
		WHERE an_code = '".$an_code."'
		AND DATE_FORMAT(an_created, '%Y-%m') = '".date('Y-m',$last_month_time)."'		
		GROUP BY DATE_FORMAT(an_created, '%e')
		";			
	$temp = $dbobj->MySQLDB_GetData($query,'ARRAY');
	foreach($temp as $val){
		$monthnos[$val['strday']] = (int) $val['info'];
	}
	$ofc_title = 'Statistics - for the last month '.date("F-Y",$last_month_time);
	$ofc_labels_x = array_keys($monthnos);
	$ofc_values_x = array_values($monthnos);
	$ofc_range_max = max($ofc_values_x)+5;
	$ofc_range_step = ceil($ofc_range_max/10);
	$ofc_legend_x = 'Days in the last month - '.date('F-Y',$last_month_time);
	$ofc_legend_y = 'Visitors';	
	$ofc_unique_id = 'ofc_last_m';	
	include(BASEPATH . 'views/ofc_chart.php');
}

//--------------------------------------------------------

/** 
 * Get OFC Chart Data for Current Week
 *
 * @descp Get OFC jason array data for Current Week
 * @access public
 * @param  NA	 
 * @return void
 */
function get_ofc_data_cur_w()
{
	global $dbobj, $proj_config;
	//get days in a month
	$no_of_days = 7;
	for($i = 1; $i <= $no_of_days ; $i++){		
		$day_of_week = date("jS-D",mktime(0,0,0,date('m'),(date('d')-$i),date('Y')));		
		$monthnos[$day_of_week] = 0;
		$montharr[] = $day_of_week;
	}
	//This will give us yesterdays timestamp
	$curr_day_of_week = date("Y-m-d H:i:s",mktime(23,59,59,date('m'),(date('d')-1),date('Y')));		
	//This will give us last seventh day timestamp from yesterday
	$last_day_of_week = date("Y-m-d H:i:s",mktime(0,0,0,date('m'),(date('d')-7),date('Y')));		
		
	$an_code = $_SESSION['domain_sel']['c_code'];
	$query = "SELECT DATE_FORMAT(an_created, '%D-%a') as strday, COUNT(an_id) as info
		FROM ".TBL_ANA_DATA."
		WHERE an_code = '".$an_code."'
		AND DATE_FORMAT(an_created, '%Y-%m') = '".date('Y-m')."'		
		AND (
			DATE_FORMAT(an_created, '%Y-%m-%d %H:%i:%s') <= '".$curr_day_of_week."'		
			AND
			DATE_FORMAT(an_created, '%Y-%m-%d %H:%i:%s') >= '".$last_day_of_week."'
		)
		GROUP BY DATE_FORMAT(an_created, '%D-%a')
		";	
	//echo '<br>'.$query;		exit("Exit statement called..........");	
	$temp = $dbobj->MySQLDB_GetData($query,'ARRAY');
	foreach($temp as $val){
		$monthnos[$val['strday']] = (int) $val['info'];
	}
	
	$from_title = date("jS D M-Y",mktime(0,0,0,date('m'),(date('d')-7),date('Y')));
	$to_title = date("jS D M-Y",mktime(0,0,0,date('m'),(date('d')-1),date('Y'))); 
	
	$ofc_title = 'Statistics - for the week from:'.$from_title .' to:'.$to_title;
	$ofc_labels_x = array_keys($monthnos);
	$ofc_values_x = array_values($monthnos);
	$ofc_range_max = max($ofc_values_x)+5;
	$ofc_range_step = ceil($ofc_range_max/10);
	$ofc_legend_x = 'Days in the week';
	$ofc_legend_y = 'Visitors';	
	$ofc_unique_id = 'ofc_cur_w';	
	include(BASEPATH . 'views/ofc_chart.php');
}
/*************************************************************/

/*************************************************************/
//Do not change this part
include(BASEPATH . 'views/header.php');//include header file
include(BASEPATH . 'views/an_list.php');//include body part
include(BASEPATH . 'views/footer.php');//include footer file
/************************************************************/

?>